<template>
  <div class="article-list" ref="article-list">
    <van-pull-refresh v-model="isRefreshLoading" @refresh="onRefresh" :success-text="refreshSuccessText" success-duration="1500">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <article-item :articles="articles"></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '../api/article.js'
import ArticleItem from './article-item.vue'
import { debounce } from 'lodash'

export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      articles: [],
      loading: false,
      finished: false,
      timestamp: null,
      isRefreshLoading: false,
      refreshSuccessText: '',
      scrollTop: 0 // 列表滚动到顶部的距离
    }
  },
  methods: {
    async onLoad () {
      /*
        1.请求获取数据
       */
      const { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: this.timestamp || Date.now(),
        with_top: 1
      })
      console.log('onLoad', data)
      /*
        2.挂载数据
       */
      const { results } = data.data
      this.articles.push(...results)
      /*
        3.设置本次加载状态结束，它才可以判断是否需要加载下一次，否则就会停在这里
       */
      this.loading = false
      /*
        4.数据全部加载完成
       */
      if (results.length) {
        // 更新获取下一页数据的页码
        this.timestamp = data.data.pre_timestamp
      } else {
        // 没有数据了，结束加载状态
        this.finished = true
      }
    },
    async onRefresh () {
      /*
        1.获取数据
       */
      const { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: Date.now(),
        with_top: 1
      })
      console.log('onRefresh', data)
      /*
        2.更新数据
       */
      const { results } = data.data
      this.articles.unshift(...results)
      /*
        3.关闭刷新的状态
       */
      this.isRefreshLoading = false
      this.refreshSuccessText = `更新了${results.length}条数据`
    }
  },
  mounted () {
    const articleList = this.$refs['article-list']
    articleList.onscroll = debounce(() => {
      this.scrollTop = articleList.scrollTop
    }, 50)
  },
  activated () {
    // 缓存的组件独有的状态，组件被激活
    this.$refs['article-list'].scrollTop = this.scrollTop
  }
}
</script>

<style scoped>
.article-list {
  position: fixed;
  bottom: 50px;
  top: 90px;
  left: 0;
  right: 0;
  overflow-y: auto;
}
</style>
